package com.clob.dao.impl;

import com.clob.dao.Dao;
import com.clob.dao.DaoAssistant;
import com.clob.dbtools.JDBCTools;
import com.clob.exception.DBException;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDaoImpl implements Dao {

    private DaoAssistant daoAssistant;

    {
        daoAssistant=  new DaoAssistant();
    }

    /**
     * 获取  List<Map<String, Object>>
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> findAllListMap(String sql, Object ... objs) {
        Connection connection = JDBCTools.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            daoAssistant.initParameters(preparedStatement, objs);
            resultSet = preparedStatement.executeQuery();
            List<String> columnLables = daoAssistant.columnLables(resultSet);
            ResultSetMetaData metaData ;
            Map<String, Object> columnMap ;
            while (resultSet.next()){
                metaData = resultSet.getMetaData();
                columnMap = new HashMap<>();
                for (String columnLable : columnLables) {
                    Object columnValue = resultSet.getObject(columnLable);
                    columnMap.put(columnLable, columnValue);
                }
                list.add(columnMap);
            }
        } catch (SQLException e) {
            throw new DBException(this.getClass() + "执行查询异常");
        } finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return list;
    }
}
